package cn.lfzj.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.lfzj.model.BusLine;
import cn.lfzj.service.BusLineService;

@CrossOrigin
@Controller
@RequestMapping("/busLine")
public class BusLineController {
	@Autowired
	private BusLineService busLineService;

	/**
	 * 显示全部线路
	 */
	@RequestMapping("showAll")
	public String showBusLine(Model model) {
		model.addAttribute("busLineList", busLineService.findAll());
		return "manager/showBusLine";
	}

	/**
	 * 全部线路JSON
	 */
	@RequestMapping(value = "lineJson", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String lineJson(BusLine busLine) {
		JSONObject json = new JSONObject();
		json.put("line", busLineService.findAll());
		return json.toJSONString();
	}

	/**
	 * 显示新增页
	 */
	@RequestMapping("showAdd")
	public String showAdd(Model model) {
		return "manager/addBusLine";
	}

	/**
	 * 新增线路
	 */
	@RequestMapping("add")
	@ResponseBody
	public String add(@Valid BusLine busLine, BindingResult result) {
		JSONObject json = new JSONObject();
		int code = -1;
		if (!result.hasErrors()) {
			code = busLineService.addBusLine(busLine);
		}
		json.put("code", code);
		return json.toJSONString();
	}

	/**
	 * 删除线路
	 */
	@RequestMapping("del")
	public String del(int lineId) {
		busLineService.delBusLine(lineId);
		return "forward:/busLine/showAll";
	}

	/**
	 * 显示修改页
	 */
	@RequestMapping("showUpd")
	public String showUpd(Model model, int lineId) {
		model.addAttribute(busLineService.selById(lineId));
		return "manager/updBusLine";
	}

	/**
	 * 修改线路
	 */
	@RequestMapping("upd")
	@ResponseBody
	public String updBusLine(@Valid BusLine busLine, BindingResult result) {
		JSONObject json = new JSONObject();
		int code = -3;
		if (!result.hasErrors()) {
			code = busLineService.updBusLine(busLine);
		}
		json.put("code", code);
		return json.toJSONString();
	}

}
